const keyTypeMap = {
  '': '全部',
  0: '手机钥匙',
  1: '临时钥匙',
  2: '蓝扣钥匙',
  99: '管家钥匙'
}

function getRenterListAndHouseMaster(data) {
  $('.popup-bg').show()
  $.ajax({
    type: 'GET',
    url: pgApiUtils(optimizedBaseUrl + requestApiUrl.LandlordInfo)
      .setRequestUrl('select=house(housenumber,operation(operator_name,operator_mobile,simpleaddr,n_house))&')
      .eqVal('lockid:' + data.lockid)
      .order('lockid'),
    beforeSend: function (xhr) {
      xhr.setRequestHeader('Authorization', tokenPgAuth);
      xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
    }
  }).done((res) => {
    $('.popup').show()
    $('.popup #masterNews').html(`
        <div class="item">
            <div class="top">房东姓名</div>
            <div class="bottom">${res[0].house.operation.operator_name || '--'}</div>
        </div>
        <div class="item">
            <div class="top">房东联系方式</div>
            <div class="bottom">${res[0].house.operation.operator_mobile || '--'}</div>
        </div>
        <div class="item">
            <div class="top">房屋地址</div>
            <div class="bottom">${res[0].house.operation.simpleaddr || '--'}</div>
        </div>
        <div class="item">
            <div class="top">房间号</div>
            <div class="bottom">${res[0].house.housenumber || '--'}</div>
        </div>
        <div class="item">
            <div class="top">拥有房间总数</div>
            <div class="bottom ta">${res[0].house.operation.n_house || '--'}</div>
        </div>
        `)
  }).fail((err) => {
    console.log(err)
  })
  $.ajax({
    type: 'GET',
    url: pgApiUtils(optimizedBaseUrl + requestApiUrl.CheckInPerson)
      .setRequestUrl('select=valid_from,valid_to,user(name,phone,identifier,headpicture)&userrole=neq.255&keytype=in.(0,2)&keystate=is.true&')
      .eqVal('lockid:' + data.lockid)
      .order('valid_from.desc,valid_to.desc,keyid'),
    beforeSend: function (xhr) {
      xhr.setRequestHeader('Authorization', tokenPgAuth);
      xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
    }
  }).done((res) => {
    console.log('当前入住的人员情况', res)
    let text = ''
    let picList = []
    var $userItems = $('.popup #userItems');
    if (res.length != 0) {
      res.forEach(item => {
        text += `
          <div class="item">
            <img src="lib3/img/mrtx.png" alt="">
            <div class="item-head">
              <div class="left">姓名</div>
              <div class="right">${item.user.name}</div>
            </div>
            <div class="item-head">
              <div class="left">身份证号</div>
              <div class="right">${item.user.identifier}</div>
            </div>
            <div class="item-head">
              <div class="left">联系方式</div>
              <div class="right">${item.user.phone}</div>
            </div>
            <div class="item-head">
              <div class="left">发放时间</div>
              <div class="right">${item.valid_from ? item.valid_from.replace(/T/g, " ") : "--"}</div>
            </div>
            <div class="item-head">
              <div class="left">失效时间</div>
              <div class="right">${item.valid_to ? item.valid_to.replace(/T/g, " ") : "--"}</div>
            </div>
          </div>`
        var img = new Image();
        img.onload = function () {
        }
        img.src = `${item.user.headpicture}`;
        img.onerror = function () {
          img.src = 'lib3/img/mrtx.png';
        }
        picList.push(img)
      })

      if (res.length <= 5) {
        $userItems.addClass('mt50')
      } else {
        $userItems.removeClass('mt50')
      }
      $userItems.html(text)
      picList.forEach((item, index) => {
        $('.popup .userItems .item').eq(index).find('img').replaceWith($(item))
      })
    } else {
      $userItems.html(`<div class="no-pic"><img src="lib3/img/pic_nopeople.png" alt=""><p>暂无租客信息</p></div>`)
    }

  }).fail((err) => {
    console.log(err)
  })
}    //一房多人-房东信息，入住人员信息

//更换房客频繁-房东信息，周期内发放的钥匙情况
function KeysIssuedDuringTheCycle(data) {
  $('.popup-bg').show()
  $.ajax({
    type: 'GET',
    url: pgApiUtils(optimizedBaseUrl + requestApiUrl.LandlordInfo)
      .setRequestUrl('select=house(housenumber,operation(operator_name,operator_mobile,simpleaddr,n_house))&')
      .eqVal('lockid:' + data.lockid)
      .order('lockid'),
    beforeSend: function (xhr) {
      xhr.setRequestHeader('Authorization', tokenPgAuth);
      xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
    }
  }).done((res) => {
    console.log('弹窗', res)
    $('.popup5-1').show()
    $('.popup5-1 #masterNews5').html(`
        <div class="item">
            <div class="top">房东姓名</div>
            <div class="bottom">${res[0].house.operation.operator_name || '--'}</div>
        </div>
        <div class="item">
            <div class="top">房东联系方式</div>
            <div class="bottom">${res[0].house.operation.operator_mobile || '--'}</div>
        </div>
        <div class="item">
            <div class="top">房屋地址</div>
            <div class="bottom">${res[0].house.operation.simpleaddr || '--'}</div>
        </div>
        <div class="item">
            <div class="top">房间号</div>
            <div class="bottom">${res[0].house.housenumber || '--'}</div>
        </div>
        <div class="item">
            <div class="top">拥有房间总数</div>
            <div class="bottom ta">${res[0].house.operation.n_house || '--'}</div>
        </div>
        `)
  }).fail((err) => {
    console.log(err)
  })


  var keyString = ''
  if (data.stats_per_lock_for_formal_last_15day) {
    var keysInfo = data.stats_per_lock_for_formal_last_15day.granted_keys || [];
    keyString = keysInfo.join(',')
  }
  $.ajax({
    type: 'GET',
    url: pgApiUtils(optimizedBaseUrl + requestApiUrl.CheckInPerson)
      .setRequestUrl('select=keyid,account,valid_from,valid_to,user(headpicture,name,identifier,phone),event_summary(tally)&')
      .inVal('keyid:' + keyString)
      .order('valid_from.desc,account'),
    beforeSend: function (xhr) {
      xhr.setRequestHeader('Authorization', tokenPgAuth);
      xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
    }
  }).done((res) => {
    console.log('周期内发放的钥匙情况', res)
    let text = ''
    let picList = []
    var $userItems5 = $('.popup5-1 #theCycleBoxList');
    if (res.length != 0) {
      res.forEach(item => {
        var tally = 0
        if (item.event_summary && item.event_summary.length != 0) {
          tally = item.event_summary[0].tally
        }
        text += `
          <div class="item">
            <img src="lib3/img/mrtx.png" alt="">
            <div class="item-head">
              <div class="left">姓名</div>
              <div class="right">${item.user.name}</div>
            </div>
            <div class="item-head">
              <div class="left">身份证号</div>
              <div class="right">${item.user.identifier}</div>
            </div>
            <div class="item-head">
              <div class="left">联系方式</div>
              <div class="right">${item.user.phone}</div>
            </div>
            <div class="item-head">
              <div class="left">发放时间</div>
              <div class="right">${item.valid_from ? item.valid_from.replace(/T/g, " ") : "--"}</div>
            </div>
            <div class="item-head">
              <div class="left">失效时间</div>
              <div class="right">${item.valid_to ? item.valid_to.replace(/T/g, " ") : "--"}</div>
            </div>
            <div class="item-head">
              <div class="left">使用总次数</div>
              <div class="right">${tally}</div>
            </div>
            
          </div>`

        $userItems5.html(text)
        var img = new Image();
        img.onload = function () {
        }
        img.src = `${item.user.headpicture}`;
        img.onerror = function () {
          img.src = 'lib3/img/mrtx.png';
        }
        picList.push(img)
      })

      if (res.length <= 5) {
        $userItems5.addClass('mt50')
      } else {
        $userItems5.removeClass('mt50')
      }
      picList.forEach((item, index) => {
        $userItems5.find('.item').eq(index).find('img').replaceWith($(item))
      })
    } else {
      $userItems5.html(`<div class="no-pic"><img src="lib3/img/pic_nopeople.png" alt=""><p>暂无信息</p></div>`)
    }

  }).fail((err) => {
    console.log(err)
  })
}

//夜间异常活动--详情页'
function getRenterListAndHouseMaster2(data) {
  $('.popup-bg').show()
  $.ajax({
    type: 'GET',
    url: pgApiUtils(optimizedBaseUrl + requestApiUrl.keyInfoExpect)
      .setRequestUrl('select=headpicture,name,phone,identifier,detailaddr,housenumber,tally_per_hour_in_night,tally_per_hour_in_dawn&')
      .eqVal('keyid:' + data.keyid),
    beforeSend: function (xhr) {
      xhr.setRequestHeader('Authorization', tokenPgAuth);
      xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
    }
  }).done((res) => {
    console.log('夜间异常活动--详情页', res)
    res = res || [{}]
    var img = new Image();
    img.onload = function () {
    }
    img.src = (res[0].headpicture) ? res[0].headpicture : 'lib3/img/mrtx.png';
    img.onerror = function () {
      img.src = 'lib3/img/mrtx.png';
    }
    var $img = $(img).addClass('avatar')
    $('.popup4 .avatar').replaceWith($img)
    $('.popup4').show()
    $('.popup4 #masterNews2').html(`
        <div class="item">
            <div class="top">姓名</div>
            <div class="bottom">${res[0].name || '--'}</div>
        </div>
        <div class="item">
            <div class="top">联系方式</div>
            <div class="bottom">${res[0].phone || '--'}</div>
        </div>
         <div class="item">
            <div class="top">身份证</div>
            <div class="bottom ta">${res[0].identifier || '--'}</div>
        </div>
        <div class="item">
            <div class="top">房屋地址</div>
            <div class="bottom">${res[0].detailaddr || '--'}</div>
        </div>
        <div class="item">
            <div class="top">房间号</div>
            <div class="bottom">${res[0].housenumber || '--'}</div>
        </div>
        `)
    var tally_per_hour_in_night = res[0].tally_per_hour_in_dawn || {}
    var tally_per_hour_in_dawn = res[0].tally_per_hour_in_dawn || {}
    var nightMap = {
      "20": 0,
      "21": 0,
      "22": 0,
      "23": 0,
      "0": 0,
      "1": 0,
      "2": 0,
    };
    var dawnMap = {
      3: 0, 4: 0, 5: 0, 6: 0
    }
    for (var key in tally_per_hour_in_night) {
      nightMap[key] = tally_per_hour_in_night[key]
    }
    for (var key in tally_per_hour_in_night) {
      dawnMap[key] = tally_per_hour_in_dawn[key]
    }
    var leftThirtyDayChart = echarts.init(document.getElementById('left-line'))
    let nightBarOption = {
      title: {
        show: true,
        text: "20:00  —  02:00",
        textStyle: {
          color: "white",
          fontSize: "14",
          fontWeight: "normal"
        },
        left: "40%",
        top: "0"
      },
      grid: {
        top: 50,
        bottom: 30
      },
      tooltip: {
        show: true,
        formatter: "{c}"
      },
      xAxis: {
        type: "category",
        boundaryGap: true,
        data: ["20:00", "21:00", "22:00", "23:00", "24:00", "01:00", "02:00"],
        axisLine: {
          lineStyle: {
            color: "white"
          }
        }
      },
      yAxis: {
        type: "value",
        name: "开门次数(次)",
        splitLine: {show: false},
        max: function (value) {
          return value.max + 2;
        },
        axisLine: {
          lineStyle: {
            color: "white"
          }
        },
        axisLabel: {
          color: "white",
          fontSize: 12
        }
      },
      color: "rgba(14,240,147,0.4)",
      series: [
        {
          data: Object.values(nightMap),
          type: "bar",
          barWidth : 60,
          areaStyle: {
            color: "rgba(14,240,147,0.4)"
          }
        }
      ]
    };
    leftThirtyDayChart.setOption(nightBarOption)

    var rightThirtyDayChart = echarts.init(document.getElementById('right-line'))
    let dawnBarOption = {
      title: {
        show: true,
        text: "04:00  —  06:00",
        textStyle: {
          color: "white",
          fontSize: "14",
          fontWeight: "normal"
        },
        left: "40%",
        top: "20"
      },
      grid: {
        top: 50,
        bottom: "30"
      },
      tooltip: {
        show: true,
        formatter: "{c}"
      },
      xAxis: {
        type: "category",
        boundaryGap: true,
        data: ["04:00", "05:00", "06:00"],
        axisLine: {
          lineStyle: {
            color: "white"
          }
        }
      },
      yAxis: {
        type: "value",
        name: "开门次数(次)",
        splitLine: {show: false},
        max: function (value) {
          return value.max + 2;
        },
        axisLine: {
          lineStyle: {
            color: "white"
          }
        },
        axisLabel: {
          color: "white",
          fontSize: 12
        }
      },
      color: "rgba(14,240,147,0.4)",
      series: [
        {
          data: Object.values(dawnMap),
          type: "bar",
          barWidth : 60,
          areaStyle: {
            color: "rgba(14,240,147,0.4)"
          }
        }
      ]
    };
    rightThirtyDayChart.setOption(dawnBarOption)
  }).fail((err) => {
    console.log(err)
  })
}


//访客基本情况informationOfVisitors
function informationOfVisitors(data) {
  $('.popup-bg').show()
  $('.popup1 #visitorBox4').html(`<div class="loading-box"><img src="./lib3/img/loading.gif" alt=""></div>`)
  var keyString = ''
  if (data.stats_per_lock_for_informal_last_7day) {
    var keysInfo = data.stats_per_lock_for_informal_last_7day.keys || [];
    keyString = keysInfo.join(',')
  }

  $.ajax({
    type: 'GET',
    url: pgApiUtils(optimizedBaseUrl + requestApiUrl.CheckInPerson)
      .setRequestUrl('select=account,valid_from,event_summary(max_opentime),user(key(account))&user.key.userrole=neq.255&user.key.keytype=in.(0,1,2)&user.key.keystate=is.true&')
      .inVal('keyid:' + keyString)
      .order('valid_from.desc,account'),
    beforeSend: function (xhr) {
      xhr.setRequestHeader('Authorization', tokenPgAuth);
      xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
    }
  }).done((res) => {
    console.log('访客基本情况弹窗', res)
    $('.popup1').show()
    var $visitorBox = $('.popup1 #visitorBox');
    var text = ''
    if (res.length != 0) {
      res.forEach(item => {
        /*var lizi = `
         <div class="item">
           <img src="lib3/img/mrtx.png" alt="">
           <div class="item-head">
             <div class="left">姓名</div>
             <div class="right">${item.user.name}</div>
           </div>
           <div class="item-head">
             <div class="left">身份证号</div>
             <div class="right">${item.user.identifier}</div>
           </div>
           <div class="item-head">
             <div class="left">联系方式</div>
             <div class="right">${item.user.phone}</div>
           </div>
           <div class="item-head">
             <div class="left">发放时间</div>
             <div class="right">${item.valid_from.replace(/T/g, " ")}</div>
           </div>
           <div class="item-head">
             <div class="left">失效时间</div>
             <div class="right">${item.valid_to.replace(/T/g, " ")}</div>
           </div>
         </div>`*/
        var timeString = '--'
        if (item.event_summary.length !== 0) {
          timeString = item.event_summary[0].max_opentime
          timeString = timeString ? timeString.replace(/T/g, "  ") : '--'
        }
        var keyNumber = 0;
        try {
          keyNumber = item.user.key.length
        } catch (err) {
          keyNumber = 0;
        }
        text += `
        <div class="item">
            <img src="./lib3/img/icon_fk.png" alt="" class="left">
            <div class="right">
                <div class="phone">${item.account}</div>
               <div class="bottom">
                  <div class="giveTime">发放时间：<span class="yellow">${!item.valid_from ? '--' : item.valid_from.replace(/T/g, "  ")}</span></div>
                  <div class="latelyTime">最近一次使用时间：<span class="yellow">${timeString}</span></div>
                  <div class="nums">有效钥匙数量：<span class="yellow">${keyNumber}</span></div>
              </div>
             </div>
        </div>`
      })
      $visitorBox.html(text)
    } else {
      $visitorBox.html(`<div class="no-pic"><img src="lib3/img/pic_nopeople.png" alt=""><p>暂无访客信息</p></div>`)
    }
  }).fail((err) => {
    console.log(err)
  })
}

//住所频繁更换(一人多处住所人员)左右弹框
function frequentRoomChanger(data, index) {
  $('.popup7 #personDetaileTitle').html(index === 7 ? `住所频繁更换人员` : '一人多处住所人员')
  $('.popup7 #houseDetaileTitle').html(index === 7 ? `住所更换房间信息` : '入住房间信息')
  $('.popup-bg').show()
  $.ajax({
    type: 'GET',
    url: pgApiUtils(optimizedBaseUrl + requestApiUrl.personInfo)
      .setRequestUrl('select=*&')
      .eqVal('identifier:' + data.identifier),
    beforeSend: function (xhr) {
      xhr.setRequestHeader('Authorization', tokenPgAuth);
      xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
    }
  }).done((response) => {
    console.log('左弹窗-住所频繁更换人员', response)
    let picList = []
    var res = {};
    if (response && response.length != 0) {
      res = response[0]
    }
    res.phones = res.phones || [];
    var detailAddr = '--'
    var valid_from = '--'
    if (res.key_details && res.key_details.length !== 0) {
      detailAddr = res.key_details[0].detailaddr || '--'
      valid_from = res.key_details[0].valid_from.replace(/T/g, " ") || '--'
    }
    $('.popup7').show()
    $('.popup7 #verticalBox7').html(`
          <div class="item">
            <div class="top">姓名</div>
            <div class="bottom">${res.name || '--'}</div>
          </div>
          <div class="item">
            <div class="top">入住房间数</div>
            <div class="bottom">${res.tally_houses || '--'}</div>
          </div>
          <div class="item">
            <div class="top">身份证</div>
            <div class="bottom">${res.identifier || '--'}</div>
          </div>
          <div class="item">
            <div class="top">联系方式</div>
            <div class="bottom">${res.phones.join(',') || '--'}</div>
          </div>
          <div class="item">
            <div class="top">最近一次活跃地点</div>
            <div class="bottom">${detailAddr}</div>
          </div>
          <div class="item">
            <div class="top">最近一次活跃时间</div>
            <div class="bottom">${valid_from}</div>
          </div>
       `);
    var img = new Image();
    img.onload = function () {
    }
    img.src = (res.headpictures && res.headpictures.length !== 0) ? res.headpictures[0] : 'lib3/img/mrtx.png';
    img.onerror = function () {
      img.src = 'lib3/img/mrtx.png';
    }
    var $img = $(img).addClass('avatar')
    $('.popup7 .avatar').replaceWith($img)
  }).fail((err) => {
    console.log(err)
  })




//右弹窗-住所更换房间信息
  $.ajax({
    type: 'GET',
    url: pgApiUtils(optimizedBaseUrl + requestApiUrl.personInfo)
      .setRequestUrl('select=*&')
      .eqVal('identifier:' + data.identifier),
    beforeSend: function (xhr) {
      xhr.setRequestHeader('Authorization', tokenPgAuth);
      xhr.setRequestHeader('Accept-Profile', 'api-ailock-analysis-v1');
    }
  }).done((response) => {
    var res = {};
    if (response && response.length != 0) {
      res = response[0]
    }
    let text = ''
    let picList = []
    var $userItems7 = $('.popup7 #userItems7');
    if (res.key_details && res.key_details.length != 0) {
      res.key_details.forEach(item => {
        var tally = 0
        if (item.event_summary && item.event_summary.length != 0) {
          tally = item.event_summary[0].tally
        }
        text += `
     <div class="list">
                        <div class="rows">
                            <div class="left">地址</div>
                            <div class="right">${item.detailaddr || '--'}</div>
                        </div>
                        <div class="rows">
                            <div class="left">房间号</div>
                            <div class="right">${item.housenumber || '--'}</div>
                        </div>
                        <div class="rows">
                            <div class="left">钥匙类型</div>
                            <div class="right">${keyTypeMap[item.keytype || ''] || '--'}</div>
                        </div>
                        <div class="rows">
                            <div class="left">发放时间</div>
                            <div class="right">${item.valid_from ? item.valid_from.replace(/T/g, " ") : "--"}</div>
                        </div>
                        <div class="rows">
                            <div class="left">到期时间</div>
                            <div class="right">${item.valid_to ? item.valid_to.replace(/T/g, " ") : "--"}</div>
                        </div>
                        <div class="rows">
                            <div class="left">最近开门时间</div>
                            <div class="right">${item.last_open_at ? item.last_open_at.replace(/T/g, " ") : "--"}</div>
                        </div>
                    </div>
         
 `
        $userItems7.html(text)

      })
    }
  }).fail((err) => {
    console.log(err)
  })
}

